package com.psychologyCommunity.Community.Contoller;

import com.psychologyCommunity.Community.entity.Event;
import com.psychologyCommunity.Community.entity.User;
import com.psychologyCommunity.Community.event.EventProducer;
import com.psychologyCommunity.Community.service.LikeService;
import com.psychologyCommunity.Community.util.CommunityConstance;
import com.psychologyCommunity.Community.util.CommunityUtil;
import com.psychologyCommunity.Community.util.HostHolder;
import com.psychologyCommunity.Community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LikeController implements CommunityConstance {
    @Autowired
    private LikeService likeService;
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HostHolder hostHolder;
    @RequestMapping(path = "/like",method = RequestMethod.POST)
    @ResponseBody
    public String like(int entityType,int entityId,int entityUserId,Integer postId) {
        //当你点赞的时候 肯定是针对某个实体点赞，
        User user = hostHolder.getUser();
        //点赞
        likeService.like(user.getId(),entityType,entityId,entityUserId);
        //数量 --先获取数量
        long likeCount=likeService.findEntityLikeCount(entityType,entityId);
        //状态
        int likeStates = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
        //返回的结果
        Map<String,Object> map=new HashMap<>();
        map.put("likeCount",likeCount);
        map.put("likeStatus",likeStates);

        //点赞完以后再去触发事件，点赞是赞的时候去通知目标作者，取消赞就不用了
        if(likeStates==1){
            Event event=new Event()
                    .setTopic(TOPIC_LIKE)
                    .setEntityId(hostHolder.getUser().getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setUserId(entityUserId)
                    .setData("postId",postId);
            //触发事件
            eventProducer.fireEvent(event);
        }
        //这得注意一下，只有当点赞的实体类型是帖子的时候才进行加分
        if(entityType== ENTITY_TYPE_POST){
            //计算帖子的分数
            String postScoreKey = RedisKeyUtil.getPostScoreKey();
            //用Set而不用队列的原因：存在缓存中的数据 无需排序并且要去重-- 可能这个用户点赞由清除又点赞进行多次，那么重复数据算起来没有意义，
            redisTemplate.opsForSet().add(postScoreKey,postId);//加精时需要加分，放到缓存里
        }

        //正确的话返回0，提示返回null，数据返回给页面
        return CommunityUtil.getJSONString(0,null,map);

    }
}
